// 页面加载完成后执行
document.addEventListener('DOMContentLoaded', () => {
    // 检查是否已登录
    const token = localStorage.getItem('token');
    if (token) {
        window.location.href = '/';
        return;
    }

    // 添加表单提交事件监听器
    const loginForm = document.getElementById('loginForm');
    loginForm.addEventListener('submit', handleLogin);
});

// 处理登录
async function handleLogin(event) {
    event.preventDefault();

    const username = document.getElementById('username').value;
    const password = document.getElementById('password').value;

    try {
        const response = await fetch('/api/users/login', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ username, password })
        });

        if (!response.ok) {
            const error = await response.json();
            throw new Error(error.error || '登录失败');
        }

        const data = await response.json();
        
        // 保存token和用户信息
        localStorage.setItem('token', data.token);
        localStorage.setItem('user', JSON.stringify(data.user));

        // 跳转到首页
        window.location.href = '/';
    } catch (error) {
        console.error('登录失败:', error);
        alert(error.message || '登录失败，请检查用户名和密码');
    }
} 